package sealte.mytable.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 数据库连接工具类
 * 2012-07-06 10:27
 * @author SEALTE
 *
 */
public class DBConnection {
	
	public String db_style = null;
	private String url = null;
	private String ip_port = null;
	private String dbName = null;
	private String user = null;
	private String password = null;
	
	public DBConnection(String db_style,String db_ip_port,String db_name,String user,String password){
		this.db_style = db_style;
		this.ip_port = db_ip_port;
		this.dbName = db_name;
		this.user = user;
		this.password = password;
	}
	
	public String[] injectDBDriver(){
		String[] msg = new String[2];
		if(null!=db_style){
			if(db_style.equals("MySQL")){
				try {
					Class.forName("com.mysql.jdbc.Driver");
					url = "jdbc:mysql://" + ip_port + "/" + dbName;
				} catch (ClassNotFoundException e) {
					return new String[]{"N","db_Driver--ClassNotFound\n"+e.getMessage()};
				}
				msg[0] = "Y";
				msg[1] = "";
			}else if(db_style.equals("Oracle")){
				try {
					Class.forName("oracle.jdbc.driver.OracleDriver");
					url = "jdbc:oracle:thin:@" + ip_port + ":" + dbName;
				} catch (ClassNotFoundException e) {
					return new String[]{"N","db_Driver--ClassNotFound\n"+e.getMessage()};
				}
				msg[0] = "Y";
				msg[1] = "";
			}else{
				msg[0] = "N";
				msg[1] = "DBConnection-injectDBDriver-->Please give me an correct db_style!";
			}
		}else{
			msg[0] = "N";
			msg[1] = "DBConnection-injectDBDriver-->db_style is null!";
		}
		return msg;
	}
	
	public Connection getConnection() throws Exception{
		return DriverManager.getConnection(url, user, password);
	}
	
	public void close(Connection conn,PreparedStatement ps,ResultSet rs){
		try{
			if(null!=rs){
				rs.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(null!=ps){
					ps.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try{
					if(null!=conn){
						conn.close();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	public void close(Connection conn,Statement stmt,ResultSet rs){
		try{
			if(null!=rs){
				rs.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(null!=stmt){
					stmt.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try{
					if(null!=conn){
						conn.close();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	public void close(Connection conn,PreparedStatement ps){
		try{
			if(null!=ps){
				ps.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(null!=conn){
					conn.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
